<template>
    <el-dialog
        title="选择成分材料"
        class='product-dialog'
        :visible.sync="showw"
        @close="closeEvt"
        append-to-body
        width="1200px"
        >
        <page-layout>
            <template v-slot:header>
                <el-input v-model="query.name" placeholder="输入产品名字查询" size='small'/>
                <el-button type='primary' size='small' @click="queryEvt">查询</el-button>
            </template>

            <el-table :data="tableData"
                style="width: 100%"
                ref="multipleTable"
                height="100%"
                @selection-change="handleSelectionChange"
                size='small'>
                <el-table-column type="selection"  width="55" fixed />
                <el-table-column prop="name" label="产品名字" width="130" fixed/>
                <el-table-column prop="state" label="状态" width="100">
                    <template v-slot="{ row:{ state }}">
                        <div  
                        :class="[state == 'sales' ? 'product-state sale' : state == 'finish' ? 'product-state' : 'product-state new' ]"
                         ref="stateClass">
                                {{state | stateFilter(_this) }}
                        </div>

                    </template>
                </el-table-column>
                <el-table-column prop="type" label="类型" width="80">
                    <template v-slot="data">
                        <div>{{ data.row.type | typeFilter(medicalType) }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="level" label="级别" width="80">
                    <template v-slot="data">
                        <div>{{ data.row.level | typeFilter(levelType) }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="brand" label="品牌" width="130"/>
                <el-table-column prop="place" label="产地" show-overflow-tooltip width="200"/>
                <el-table-column prop="price" label="售价" width="100"/>
                <el-table-column prop="remark" label="备注" show-overflow-tooltip width="220"/>
            </el-table>

            <template v-slot:footer>
                <el-pagination :page-sizes="[20, 35, 45, 55]"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page = "query.page"
                    :page-size="query.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"/>
            </template>
             </page-layout>
             <template slot="footer" class="dialog-footer">
                <el-button @click="closeEvt">取 消</el-button>
                <el-button type="primary" @click="confirmEvt">确 定</el-button>
            </template>
    </el-dialog>
</template>

<script>
import { productListApi,dictInfoApi } from '../../../apis/productApi.js'
export default {
    props:{
        value:{
            type:Boolean,
            required: true
        }
    },
    data() {
        return {
            showw:false,
            tableData: [],
            total:0,
            query: {
                page: 1,
                size: 20,
                name: ''
            },
            timer:null,
            medicalType: [],
            levelType: [],
            _this : null,  //this
            selectList:[],
            loading:true
        }
    },
    watch:{
        value(val){
            this.showw = val
        }
    },
    filters:{ //过滤器 上方使用时用 | 隔开
        typeFilter(val,arr){
            // console.log(val,arr)
            let type = arr.find(it=> it.code == val )
            if(!type) return val
            return type.name
        },
        stateFilter(val,_this){
            let stateName = ''
            if(val == 'sales'){
                return stateName = '在售'
            }else if(val == 'new'){
                return stateName = '新建'
            }else{
                return stateName = '已下架'
            }
        }
    }
    ,
    async mounted() {
        Promise.all(
            [
                dictInfoApi('MEDICAL'),
                dictInfoApi('PRODUCT_LEVEL')
            ]).then(d=>{
               if(d[0].code == 200){ this.medicalType = d[0].data.rows }
               if(d[1].code == 200){ this.levelType = d[1].data.rows }
            })
        this._this = this
        this.getList()
    },
    methods:{
        closeEvt(){
            this.$emit('input',false)
        },
        show(row){
            console.log(row)
        },
        queryEvt(){
            this.query.page = 1
            this.getList()
        },
        handleSizeChange(size){
            // setTimeout()
            this.query.size = size
            if(this.timer){
                clearTimeout(this.timer)
            }
            this.timer = setTimeout(()=>{
                this.getList()
            },100)
            
            // console.log('size',size);
        },
        handleCurrentChange(curren){
            this.query.page = curren
            if(this.timer){
                clearTimeout(this.timer)
            }
            this.timer = setTimeout(()=>{
                this.getList()
            },100)
            
            // console.log('curren',curren);
        },
       async getList(){
        this.loading = true
            let result = await productListApi(this.query)
            if (result.code === 200) {
                this.tableData = result.data.rows
                this.total = result.data.count
            }
            setTimeout(()=>{
                //在页面切换的时候会先触发handleSelectionChange，再是toggleRowSelection，
                //切换回来的时候先触发toggleRowSelection，再触发handleSelectionChange
                //所以解决方案应该是调用toggleRowSelection方法时不触发handleSelectionChange
                // // Uncaught TypeError: Cannot read properties of undefined (reading 'toggleRowSelection')
                if (!!this.$refs.multipleTable) {
                    console.log('------toggleRowSelection')
                    this.selectList.forEach(it=>{
                        //row undefined错误 在页面切换就是发送页面请求初始化调用toggleRowSelection，不要给selectedRows数据赋值，就是上方的解决方案
                        let row = this.tableData.find(item=> item.id == it.id)
                        if(!!row){
                            //设置选中的数据   toggleRowSelection会触发selection-change事件 即handleSelectionChange方法
                            this.$refs.multipleTable.toggleRowSelection(row,true)
                        }
                    })
                }
                //  页面切换完成后，节流标志管理，才能调用handleSelectionChange
                setTimeout(()=>{
                    this.loading = false
                },100)

            })
        },
        handleSelectionChange(data){
            if(!this.loading){//节流关闭时才进入
                console.log('------handleSelectionChange')
                //循环遍历删除选中的
                this.tableData.forEach(it=>{
                    //是否有选中的
                    let hasPick = this.selectList.findIndex(item => item.id == it.id)
                    //循环删除选中的
                    if(hasPick > -1) this.selectList.splice(hasPick,1)
                })
                //选择发生变化时如上面这样删除选中，把最后选中的数据一起放入选中
                this.selectList = this.selectList.concat(data)
            }

        },
        confirmEvt(){
            this.$emit('productAdd',this.selectList) 
            this.closeEvt()
        }

    }
}
</script>

<style lang="less" scoped>
        .product-state {
        color: #999;
        &::before {
            content: '';
            display: inline-block;
            vertical-align: middle;
            width: 6px;
            height: 6px;
            border-radius: 6px;
            background: #999;
            margin-right: 6px;
        }
        &.sale {
            color: #409EFF;
            &::before {
                background: #409EFF;
            }
        }
        &.new {
            color: #85ce61;
            &::before {
                background: #85ce61;
            }
        }
    }
</style>